/**
 * 
 */
package com.cipe.cmrs.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cipe.cmrs.model.User;


/**
 * @author Incepio
 *
 */

public class UserSessionFilter implements Filter {
	
	/**
	 * This filter is invoked for all the /secure/* links and checks whether there is a valid user present in the 
	 * session or not. If latter then it redirects the response to use login page with a warning message.
	 * 
	 */
	
	private Logger logger = LoggerFactory.getLogger(UserSessionFilter.class);
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		logger.debug("UserSessionFilter doFilter called..");
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		HttpSession session = request.getSession();
		
		Integer userId = (Integer) session.getAttribute(User.LOGGED_IN_USER_KEY);
		logger.debug("doFilter() user = " + userId);
		logger.debug("URL: " + request.getRequestURI());
		if(userId == null) {		
			response.sendRedirect(request.getContextPath() + "/showLogin.do"); 
			return;
		}	
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
	
	@Override
	public void destroy() {
	}
}	
